const locations = {
		lat:'',
		lng:'',
		address:''
}


const checkLocationAuth = function(){
	console.log("checkLocationAuth");
	uni.getSetting({
	    success(res){
	        if(res.authSetting['scope.userLocation']){
	            console.log("已授权地理位置")
				getLocationInfo();
	        }else if(!res.authSetting['scope.userLocation']){
				console.log("未授权地理位置。。。");
				getLocationAuthorizeInfo();
	        }
	    }
	}) 
}


const getLocationAuthorizeInfo = function(){
	
		uni.authorize({
			scope: 'scope.userLocation',
			success() { // 允许授权
				console.log("授权地理位置");
				getLocationInfo();
				//that.getLocationInfo();
			},
			fail(){    // 拒绝授权
				openLocationConfirm();
				console.log("你拒绝了授权，无法获得周边信息")
			}
		});
	return locations;
}

const openLocationConfirm = function(){
	uni.showModal({
		title: '请求授权当前位置',
		content: '该程序需要地理位置，请确认授权',
		showCancel: false,
		success: (res)=> {
			if (res.confirm) {
				uni.openSetting({
					success(res) {
						if (res.authSetting['scope.userLocation']) {
							console.log("已授权");
							getLocationInfo();
						}else if(!res.authSetting['scope.userLocation']){
							console.log("地理位置授权失败")
							checkLocationAuth();
							
						}
					}
				});// 打开地图权限设置
			}
		}
	});
}

/**
 * 获取定位信息
 */
const getLocationInfo = function(){  
	
	uni.getLocation({
		type: 'gcj02',
		success (res) {
			console.log("你当前经纬度是：");
			console.log(res);
			let latitude,longitude;
			latitude = res.latitude.toString();
			longitude = res.longitude.toString();
			locations.lat = latitude;
			locations.lng = longitude;
			uni.request({
				header:{
					"Content-Type": "application/text"
				},
				url:'https://apis.map.qq.com/ws/geocoder/v1/?location='+latitude+','+longitude+'&key=CDLBZ-4D4C3-7E53T-YKU2U-ELKGF-I7FWQ',
				success(re) {
					console.log("中文位置")
					console.log(re)
					
					locations.address=re.data.result.address+'';
					
					if(re.statusCode === 200){
						console.log("获取中文街道地理位置成功")
					}else{
						console.log("获取信息失败，请重试！")
					}
				 }
			});
		}
	});
	return locations;
}

const install = (Vue) => {
	Vue.prototype.$auth = {
		getLocationAuthorizeInfo,
		getLocationInfo,
		openLocationConfirm,
		checkLocationAuth
	};
}

export default {
	install
}